<template>
  <el-dialog v-model="dialog.visible" title="常用语" width="40%" @close="handleCloseDialog">
    <el-form
      v-if="dialog.visible"
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      class="form"
    >
      <el-form-item label="常用语" prop="content">
        <el-input v-model="formData.content" placeholder="请输入常用语" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          :autosize="{ minRows: 2, maxRows: 4 }"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import PhrasesAPI, { MerchantPhrasesForm } from "@/api/phrases";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "loadData"]);

const dialog = reactive({
  title: "",
  visible: false,
});
const formRef = ref();
const loading = ref(false);
const defaultFormData: MerchantPhrasesForm = {
  content: "",
  remark: "",
};
const formData = ref<MerchantPhrasesForm>({
  ...defaultFormData,
});

const formRules = reactive({
  content: [{ required: true, message: "请输入常用语", trigger: "blur" }],
});
async function handleSubmit() {
  const validate = await formRef.value.validate();
  if (!validate) return;
  try {
    if (formData.value.id) {
      await PhrasesAPI.update(formData.value);
    } else {
      await PhrasesAPI.add(formData.value);
    }
    ElMessage.success("成功");
    emit("loadData");
    handleCloseDialog();
  } catch (error) {
    console.log("error", error);
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.value = {};
  Object.assign(formData.value, defaultFormData);
  emit("update:modelValue", false); // 关闭弹窗
}

function showModal(val) {
  dialog.visible = true;
  Object.assign(formData.value, defaultFormData, val);
}

defineExpose({
  showModal,
});
</script>
<style style="scss" scoped>
::v-deep(.el-tabs__content) {
  min-height: 100px;
  display: flex;
  align-items: center;
}
</style>
